<template>
  <div>
    <fks-row
      style="margin-bottom: 20px"
      :gutter="32"
    >
      <fks-col :span="24">
        <fks-input
          v-model="loginForm.username"
          class="login-input login-username"
          :placeholder="LANG.ACCOUNT_NAME"
        />
      </fks-col>
    </fks-row>
    <fks-row :gutter="32">
      <fks-col :span="24">
        <fks-input
          v-model="loginForm.password"
          v-debounce.enter="handleLogin"
          show-password
          type="password"
          maxlength="50"
          class="login-input login-password"
          :placeholder="LANG.ACCOUNT_PWD"
        />
      </fks-col>
    </fks-row>
    <fks-row
      v-if="imgCaptchaValidate && setCaptcha"
      :gutter="32"
    >
      <Verify
        ref="verify"
        mode="pop"
        :captcha-type="captchaType"
        :img-size="{ width: '330px', height: '155px' }"
        @success="success"
      />
    </fks-row>
    <div
      style="
        display: flex;
        justify-content: space-between;
        height: 36px;
        margin-top: 20px;
        line-height: 36px;
"
    >
      <fks-checkbox
        v-if="loginType == 'STANDARD'"
        v-model="remember"
      >
        {{ LANG.PWD_REMEMBER }}
      </fks-checkbox>

      <div
        style="font-weight: 500; font-size: 14px; color: #555; cursor: pointer"
        @click="editPassword"
      >
        {{ LANG.FORGOT_PASSWORD }}
      </div>
    </div>
    <div class="login-button-container">
      <fks-button
        v-debounce="handleLogin"
        type="primary"
        :loading="loading"
      >
        {{ LANG.CLICK_LOGIN }}
      </fks-button>
    </div>
  </div>
</template>
<script>
import * as stateTypes from '@/store/State/stateTypes'
import { mapState } from 'vuex'
import { GRANT_TYPE } from '@/config/enums'
import { getErrorParams } from '../api'
import Verify from './Verify'
import { pwdEncrypt } from '@/utils/encryption/pwd'
import debounce from 'throttle-debounce/debounce'
import { uuid } from '@/utils/util'
export default {
  name: 'AccountLogin',
  components: { Verify },
  data() {
    return {
      setCaptcha: true, //验证码关闭时一直不显示
      //  errorParams: {},
      errorCount: 100000,
      captchaImg: '',
      loginType: 'STANDARD',
      imgCaptchaValidate: false,
      captcha_key: '',
      img_key: '',
      loginForm: {
        username: '',
        password: '',
        img_code: ''
      },
      remember: false,
      loading: false
    }
  },
  computed: {
    ...mapState([stateTypes.INTERFACE_CONFIG, stateTypes.LOGIN_STRATEGY]),
    captchaType() {
      return this.$store.state[stateTypes.LOGIN_STRATEGY].captchaType
    },
    portalId() {
      return this.$store.state.portal.id
    }
  },
  watch: {
    'loginForm.username'(val) {
      this.updataErrorParam(val)
    }
  },
  mounted() {
    this.updataErrorParam = debounce(500, this.getErrorNum)
  },
  created() {
    this.loginForm.username = this.$storage.get('username')
    if (this.$storage.get('rememberMe') == 'true') {
      this.remember = true
      this.loginForm.password =
        (this.$storage.get('password') &&
          window.atob(this.$storage.get('password'))) ||
        ''
    }
    if (this.loginStrategy.useCaptcha) {
      //登录策略的错误次数
      this.errorCount = this.loginStrategy.errorCount
    }
  },
  methods: {
    //滑块验证码验证成功后再进行登录
    success(params) {
      this.img_key = params.captchaVerification
      this.loginForm.img_code = params.captchaVerification
      let loginData = this.getLoginForm()
      if (this.checkData(loginData)) {
        this.login(loginData)
      }
    },
    //行为验证码弹出显示
    useVerify() {
      if (this.imgCaptchaValidate) {
        this.$nextTick(() => {
          this.$refs.verify.show()
        })
      }
    },
    //获取当前登录账号已经错误次数
    getErrorNum(val) {
      getErrorParams({ userName: val })
        .then((res) => {
          if (res.status) {
            if (res.data > this.errorCount - 1) {
              this.imgCaptchaValidate = true
            } else {
              this.imgCaptchaValidate = false
            }
          }
        })
        .catch(() => {})
    },
    //跳转忘记密码页面
    editPassword() {
      this.$router.push('/forget')
    },
    //根据是否开启行为验证码审查登录数据填写提示
    handleLogin() {
      if (this.imgCaptchaValidate) {
        let loginData = this.getLoginForm()
        if (this.checkData2(loginData)) {
          return this.useVerify()
        }
      } else {
        let loginData = this.getLoginForm()
        if (this.checkData(loginData)) {
          this.login(loginData)
        }
      }
    },
    //登录操作
    login(loginData) {
      this.loading = true
      this.$store
        .dispatch('userLogin', loginData)
        .then((res) => {
          this.updataStorage()
          this.loading = false
          if (this.loginStrategy.secondFA) {
            if (res.phone) {
              this.$parent.openReLogin({ phone: res.phone })
            } else {
              this.$message.error(this.LANG.NO_PHONE_TIP)
            }
            this.loading = false
          } else {
            this.redirectTo()
            this.$storage.set('depthId', uuid(16, 32))
          }
        })
        .catch(() => {
          this.loading = false
          this.updataErrorParam(this.loginForm.username)
        })
    },
    //未输入全账号、密码和验证码时提示
    checkData(loginData) {
      if (!loginData.username) {
        this.$message.error(this.LANG.ACCOUNT_NAME)
        return false
      }
      if (!loginData.password) {
        this.$message.error(this.LANG.ACCOUNT_PWD)
        return false
      }
      if (this.imgCaptchaValidate && !loginData.captcha_code) {
        this.$message.error(this.LANG.ACCOUNT_CAPTCAH)
        return false
      }
      return true
    },
    //有验证码时检查账号和密码的填写
    checkData2(loginData) {
      if (!loginData.username) {
        this.$message.error(this.LANG.ACCOUNT_NAME)
        return false
      }
      if (!loginData.password) {
        this.$message.error(this.LANG.ACCOUNT_PWD)
        return false
      }
      return true
    },
    //登录成功时更新缓存
    updataStorage() {
      this.$storage.set('login_type', this.type)
      if (this.remember) {
        this.$storage.set('rememberMe', this.remember)
        this.$storage.set(
          'password',
          //window对象方法，创建一个base-64 编码的字符串。同步操作
          window.btoa(this.loginForm.password)
        )
      }
    },

    //登录时转换处理登录数据
    getLoginForm() {
      let form = {}
      form.grant_type = GRANT_TYPE.PASSWORD
      form.username = this.loginForm.username
      if (this.loginForm.password) {
        form.password = pwdEncrypt(this.loginForm.password)
      } else {
        form.password = this.loginForm.password
      }
      if (this.loginStrategy.secondFA) {
        form.token_before = '2FA'
      }
      if (this.imgCaptchaValidate) {
        form.grant_type = GRANT_TYPE.IMG_CAPTCHA
        form.captcha_key = this.img_key
        form.captcha_code = this.loginForm.img_code
      }
      return form
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .login-username {
  .fks-input__inner {
    background: url('../../../assets/img/login/login-account.png') no-repeat 5px
      center;
  }
}

::v-deep .login-password {
  .fks-input__inner {
    background: url('../../../assets/img/login/login-password.png') no-repeat
      5px center;
  }
}

.login-button-container {
  margin-top: 48px;

  ::v-deep .fks-button {
    width: 100%;
    height: 55px;
    font-size: 18px;
  }
}
</style>